import { imapi } from './instance'
import { dateformat } from './js/utils';

const time = 1000 * 60 * 5;
let lastTime, userList = []

export default {
	//发送单聊文本消息 onMessageAttached返回临时消息,失败也会返回
	async sendMessage({ conversationID, message, conversationType = 0 }, onMessageAttached) {
		// 发送单聊 `Command` 信息
		const toConversationID = conversationID.toString(); // 对方 userID
		// const conversationType = 0; // 会话类型，取值为 单聊：0，房间：1，群组：2
		const config = {
			priority: 3, // 设置消息优先级，取值为 低：1（默认），中：2，高：3
		};

		const messageTextObj = { type: 1, message };
		const notification = {
			onMessageAttached
		}
		let data = await imapi({
			name: 'sendMessage',
			attr: 'message'
		}, messageTextObj, toConversationID, conversationType, config, notification)
		if (data.code === 0) {
			data.data = this.messageAttribute(data.data)
		}
		return data
	},
	/**
	 * 发送自定义消息
	 * 子类型subType定义
	 * 10=礼物赠送
	 * 11=礼物赠送系统消息,message自定义格式{id:1,status:0(接收)|1(拒绝),receiveUserID:1,sendUserID:1}
	 * 12=加微信
	 * 13=加微信系统消息,message自定义格式{id:1,status:0(同意)|1(拒绝),receiveUserID:1,sendUserID:1}
	 * 14=发送微信号给对方
	 * 15=会员赠送,message自定义格式会员信息
	 * 30=添加好友系统提示,message自定义格式{id:1,status:0(同意)|1(拒绝),receiveUserID:1,sendUserID:1}
	 * 31=非会员聊天记录限制，不重复发送该消息，取最后一条消息记录判断
	 * 50=组局发布成功群聊创建系统消息
	 * 51=直接加入群聊
	 * 52=邀请加入群聊
	 * 53=主动退出群聊
	 * 54=群主移除群聊
	 * 60=违禁词系统消息
	 * 15X=代码追加的消息占用
	 */
	async sendCustomMessage({ conversationID, subType, message = '', conversationType = 0 }, onMessageAttached) {
		// 发送自定义信息
		// 指定用户的 ID
		const toConversationID = conversationID.toString();
		const searchedContent = ""; // 自定义消息的检索字段。

		const zimCustomMessage = {
			type: 200,
			message, // 自定义消息的文本内容
			subType, // 具体的自定义类型 取值范围为 [0,200]
			searchedContent
		};
		// 发送消息的高级属性配置
		// const conversationType = 0; // 会话类型，取值为 单聊：0，房间：1，群组：2
		const config = {
			priority: 3, // 设置消息优先级，取值为 低：1（默认），中：2，高：3
			hasReceipt: true, //发送消息时候，该消息是否带回执。
		};
		const notification = {
			onMessageAttached
		}
		let data = await imapi({
			name: 'sendMessage',
			attr: 'message'
		}, zimCustomMessage, toConversationID, conversationType, config, notification)
		if (data.code === 0) {
			data.data = this.messageAttribute(data.data)
		}
		return data
	},
	//发送图片消息
	sendImageMessage({ conversationID, sourceType = 'album', conversationType = 0 },
		onMessageAttached, onMediaUploadingProgress) {
		const config = { priority: 3 };
		return new Promise(resolve => {
			uni.chooseImage({
				count: 1,
				sourceType: [sourceType],
				success: async (res) => {
					const file = res.tempFiles[0];
					let filePath
					// #ifdef MP-WEIXIN
					filePath = file.path;
					// #endif
					// #ifdef APP-PLUS
					filePath = plus.io.convertLocalFileSystemURL(file.path);
					// #endif
					let mediaMessageObj = {
						fileLocalPath: filePath,
						type: 11, //11=图片,12=文件,13=音频,14=视频
					};
					const notification = {
						onMessageAttached, //存在问题，不返回临时消息参数
						onMediaUploadingProgress
					};
					let data = await imapi({
						name: 'sendMediaMessage',
						attr: 'message'
					}, mediaMessageObj, conversationID.toString(), conversationType, config, notification)
					if (data.code === 0) {
						const message = this.messageAttribute(data.data)
						//这里thumbUrl字段存在问题 人工介入
						message[message.length - 1].thumbUrl = message[message.length - 1].url
						data.data = message
					}
					resolve(data)
				}
			})
		})
	},
	//发送语音消息
	async sendAudioMessage({ conversationID, filePath, duration, conversationType = 0 },
		onMessageAttached, onMediaUploadingProgress) {
		const config = { priority: 3 };
		// #ifdef APP-PLUS
		filePath = plus.io.convertLocalFileSystemURL(filePath);
		// #endif
		let mediaMessageObj = {
			fileLocalPath: filePath,
			type: 13, //11=图片,12=文件,13=音频,14=视频
			audioDuration: duration
		};
		const notification = {
			onMessageAttached,
			onMediaUploadingProgress
		};
		let data = await imapi({
			name: 'sendMediaMessage',
			attr: 'message'
		}, mediaMessageObj, conversationID.toString(), conversationType, config, notification)
		if (data.code === 0) {
			data.data = this.messageAttribute(data.data)
		}
		return data
	},
	//发送视频消息
	async sendVideoMessage({ conversationID, duration, sourceType, conversationType = 0 },
		onMessageAttached, onMediaUploadingProgress) {},
	//消息已读 处理红包
	async sendMessageReceiptsRead({ message, conversationID, conversationType = 0 }) {
		let data = await imapi({
			name: 'sendMessageReceiptsRead',
		}, [message], conversationID.toString(), conversationType)
		return data
	},
	//添加消息表态
	async addMessageReaction({ reactionType, message }) {
		let data = await imapi({
			name: 'addMessageReaction',
			attr: 'reaction'
		}, reactionType, message)
		return data
	},
	messageAttribute(v) {
		let data = [];
		//因历史遗留问题，需要过滤掉以前的自定义消息
		if (v.type === 200 && v.timestamp < 1713434927574) return []
		if (v.type === 200 && v.timestamp < 1713791437730 && (v.subType == 12 || v.subType == 13 || v.subType == 14))
			return []
		if (!lastTime || v.timestamp - lastTime > time) {
			data.push({
				// messageID: Math.random().toString().substring(2, 12),
				type: 0, //时间显示
				time: dateformat(v.timestamp)
			})
			lastTime = v.timestamp
		}
		if (v.type === 200) {
			const d = userList.find(x => x.baseInfo.userID === v.senderUserID)
			if (d) {
				v.userAvatarUrl = d.baseInfo.userAvatarUrl
				v.userName = d.baseInfo.userName
			}
			try {
				v.message = JSON.parse(v.message)
			} catch (e) {
				//小程序第一次进入message为string，后面进入就变成object了
			}
			const r = userList.find(x => x.baseInfo.userID === v.message.sendUserID)
			if (r) {
				v.message.sendUserName = r.baseInfo.userName
			}
			const m = userList.find(x => x.baseInfo.userID === v.message.receiveUserID)
			if (m) {
				v.message.receiveUserName = m.baseInfo.userName
			}
			if (v.reactions && v.reactions.length > 0) {
				v.reactionType = v.reactions[0].reactionType
			}
			data.push(v)
			return data
		}
		let list = {
			localMessageID: v.localMessageID,
			fail: false,
			messageID: v.messageID,
			conversationType: v.conversationType,
			conversationID: v.conversationID,
			sentStatus: v.sentStatus,
			receiptStatus: v.receiptStatus, //消息回执，2=收到
			type: v.type, //消息类型：1=文本，11=图片，13=音频，14=视频，200=自定义消息
			direction: v.direction, //0=自己，1=对象
			message: v.message,
			senderUserID: v.senderUserID, //发送者userid
			// timestamp: v.timestamp, //时间戳
		}
		const d = userList.find(x => x.baseInfo.userID === v.senderUserID)
		if (d) {
			list.userAvatarUrl = d.baseInfo.userAvatarUrl
			list.userName = d.baseInfo.userName
		}

		if (v.type === 11) {
			list.thumbUrl = v.thumbnailDownloadUrl;
			list.thumbWidth = v.thumbnailWidth;
			list.thumbHeight = v.thumbnailHeight > 220 ? 220 : v.thumbnailHeight;
			list.url = v.fileDownloadUrl || v.fileLocalPath;
		}
		if (v.type === 13) {
			list.duration = v.audioDuration;
			list.url = v.fileDownloadUrl || v.fileLocalPath;
		}
		// subType 自定义消息子类型
		data.push(Object.assign(list, !v.subType || { subType: v.subType }))
		return data
	},
	// 查询历史聊天记录
	async queryHistoryMessage({ conversationID, conversationType = 0 }) {
		const config = {
			nextMessage: null, // 首次获取时 nextMessage 为 null
			count: 30,
			reverse: true
		}
		lastTime = null;
		uni.setStorageSync('current_conversationID', conversationID.toString())
		userList = uni.getStorageSync('imUserInfo') || []

		let data = await imapi({
			name: 'queryHistoryMessage',
			attr: 'messageList'
		}, conversationID.toString(), conversationType, config)
		if (data.code === 0) {
			let list = [];
			data.data.forEach(v => {
				list = [...list, ...this.messageAttribute(v)]
			})
			return list
		}
		return data
	}
}